package com.ljj.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
        import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    // 定义切入点：匹配 OrderService 的三个方法
    @Pointcut("execution(* com.ljj.service.OrderService.add(..)) || " +
            "execution(* com.ljj.service.OrderService.delete(..)) || " +
            "execution(* com.ljj.service.OrderService.find(..))")
    public void serviceMethods() {}

    // ========== 1. 前置增强：add/delete/find 调用前输出一句话 ==========
    @Before("serviceMethods()")
    public void beforeAdvice() {
        System.out.println("hello, 我是一个前置增强");
    }

    // ========== 2. 后置增强：add/delete 执行后输出一句话 ==========
    @After("execution(* com.ljj.service.OrderService.add(..)) || " +
            "execution(* com.ljj.service.OrderService.delete(..))")
    public void afterAdvice() {
        System.out.println("bye, 我是一个后置增强");
    }

    // ========== 3. 获取返回值增强（使用 AfterReturning）==========
    @AfterReturning(pointcut = "serviceMethods()", returning = "result")
    public void logReturn(Object result) {
        System.out.println("方法执行完毕，返回值是: " + result);
    }

    // ========== 4. 记录方法执行时间（使用 Around）==========
    @Around("serviceMethods()")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 执行原方法
        Object result = joinPoint.proceed();

        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        System.out.println("方法 [" + joinPoint.getSignature().getName() + "] 执行耗时: " + duration + " 毫秒");

        return result; // 返回原方法结果
    }

    // ========== 5. 权限检查（前置判断，控制 add/delete 是否继续）==========
    @Before("execution(* com.ljj.service.OrderService.add(..)) || " +
            "execution(* com.ljj.service.OrderService.delete(..))")
    public void checkPermission() {
        // 模拟权限：随机数 0=有权限，1=无权限
        int permission = (int)(Math.random() * 2); // 生成 0 或 1

        if (permission == 0) {
            System.out.println("✅ 权限验证通过，可以执行操作。");
        } else {
            System.out.println("❌ 权限不足，禁止执行操作！");
            throw new SecurityException("权限不足，操作被拒绝！");
        }
    }
}